function generateCaptcha() {
    var chars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
    var captchaLength = 6;
    var captcha = "";
    for (var i = 0; i < captchaLength; i++) {
        var randomIndex = Math.floor(Math.random() * chars.length);
        captcha += chars[randomIndex];
    }
    document.getElementById("captcha").innerHTML = captcha;
}

generateCaptcha()
$('#register').click(function () {
    valid = 1
    username = $('#username').val()
    password = $('#password').val()
    code = $('#code').val()
    captcha = document.getElementById("captcha").innerHTML
    if (username == '') {
        valid = 0
        alert('用户名不能为空！')
    } else if (password == '') {
        valid = 0
        alert('密码不能为空！')
    } else if (code == '') {
        valid = 0
        alert('验证码不能为空！')
    } else if (code != captcha) {
        valid = 0
        alert('验证码输入有误！')
    }
    if (valid == 1) {
        $.ajax({
            url : 'register',
            method : 'post',
            data : {
                username : username,
                password : password
            },
            success : function (body) {
                console.log(body)
                if (body == "用户名或密码不能为空！") {
                    alert('用户名或密码不能为空！')
                } else {
                    location.assign('blog_list.html')
                }
            }
        })
    }
})

$('#login').click(function () {
    valid = 1
    username = $('#username').val()
    password = $('#password').val()
    code = $('#code').val()
    captcha = document.getElementById("captcha").innerHTML
    if (username == '') {
        valid = 0
        alert('用户名不能为空！')
    } else if (password == '') {
        valid = 0
        alert('密码不能为空！')
    } else if (code == '') {
        valid = 0
        alert('验证码不能为空！')
    } else if (code != captcha) {
        valid = 0
        alert('验证码输入有误！')
    }
    if (valid == 1) {
        $.ajax({
            url : 'login',
            method : 'post',
            data : {
                username : $('#username').val(),
                password : $('#password').val()
            },
            success : function (body) {
                console.log(body)
                if (body == "用户名或密码错误") {
                    alert('用户名或密码错误')
                } else {
                    location.assign('blog_list.html')
                }
            }
        })
    }
})